<script setup>
import {computed, onBeforeMount, onMounted, ref, watch} from 'vue';
import {ElMessage} from "element-plus";
import {useStore} from "@/stores/store.js";
import {sendWsRequest} from "@/api/toMusicInfo.js";

// const songs = [
//   { title: '歌曲1', artist: '艺术家1', cover: 'cover1.jpg', url: 'song1.mp3' },
//   { title: '歌曲2', artist: '艺术家2', cover: 'cover2.jpg', url: 'song2.mp3' },
//   { title: '歌曲3', artist: '艺术家3', cover: 'cover3.jpg', url: 'song3.mp3' },
// ];
const props = defineProps(['song', 'websocket', 'downPosition', 'isOwner'])
const emit = defineEmits(['preSong', 'nextSong']);

// const song = ref({
//   title: '歌曲1',
//   musician: '艺术家1',
//   cover: 'src/assets/img/logo.png',
//   url: 'src/assets/testMusic.m4a'
// }
// )

// const currentSongIndex = ref(0);
// 音量
const volume = ref(50);
// 进度
const position = ref(0);
// 总时长
const duration = ref(0);
const audio = ref();
// 歌单功能
// const currentSong = computed(() => songs[currentSongIndex.value]);

const isDragging = ref(false)
// function playSong(index) {
//   currentSongIndex.value = index;
//   loadAudio();
//   playAudio();
// }

function loadAudio() {
  // if (audio) {
  //   audio.value.pause();
  // }
  // audio = new Audio(currentSong.value.url);
  // 把上一首歌暂停
  if (audio.value) {
    audio.value.pause();
  }

  audio.value = new Audio(props.song.url)

  audio.value.volume = volume.value / 100;
  audio.value.onended = nextSong
  audio.value.onplay = () => {
    useStore().togetherRoomInfo.togetherPlayStatus = true
    const websocket = props.websocket

    const message = {
      type: 2,
      data: null
    }
    sendWsRequest(websocket, message)


  }
  audio.value.onpause = () => {
    useStore().togetherRoomInfo.togetherPlayStatus = false
    const websocket = props.websocket

    const message = {
      type: 3,
      data: null
    }
    sendWsRequest(websocket, message)


  }
  audio.value.onended = () => {
    emit('next-song', props.song.index)
  }

  audio.value.volume = volume.value / 100;
  audio.value.addEventListener('loadedmetadata', () => {
    console.log('总播放时间:', audio.value.duration); // 以秒为单位
    duration.value =  audio.value.duration
  })

  audio.value.ontimeupdate = () => {

    if (!isDragging.value) {
      // 只有在未拖动时更新位置
      // useStore().togetherRoomInfo.togetherMusicPosition = audio.value.currentTime / duration.value * 100
      // 为了减小一点与websocket的交流次数，减少对网络的依赖性，只有挪动才发起进度同步请求
      position.value = audio.value.currentTime / duration.value * 100

    }

  }


}


const formatTime = (time) => {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}



function playAudio() {
  audio.value.play()
}
function pauseAudio() {
    audio.value.pause()
}


function nextSong() {
  emit('next-song', props.song.index)

  loadAudio()

  playAudio()
}

function preSong() {
  emit('pre-song', props.song.index)

  loadAudio()

  playAudio()
}

function updateVolume() {
  if (audio) {
    audio.value.volume = volume.value / 100;
  }
}
function updatePosition() {
  if (audio) {
    useStore().togetherRoomInfo.togetherMusicPosition = position.value

    audio.value.currentTime = position.value / 100 * audio.value.duration


    const websocket = props.websocket
    const data = {
      content: position.value
    }
    const message = {
      type: 4,
      data: data
    }

    sendWsRequest(websocket, message)

  }
  audio.value.play()
}

// 监听 togetherMusicPosition 的变化
// watch(() => useStore().togetherRoomInfo.togetherMusicPosition, (newValue, oldValue) => {
//   if (newValue === oldValue) return
//   const websocket = props.websocket
//   const data = {
//     content: newValue
//   }
//   const message = {
//     type: 1,
//     data: data
//   }
//
//   sendWsRequest(websocket, message)
//
// })

onBeforeMount(() => {
  loadAudio()

})
onMounted(() => {
  // 根据是不是主人启动一个定时同步任务
  if (props.isOwner) {
    startSyncTask()
  }
})
// 启动同步任务
const startSyncTask = () => {

  const websocket = props.websocket
  setInterval(() => {
    console.log('定时任务执行')
    // 同步音乐和歌单
    let data = {
      musicIndex: useStore().togetherRoomInfo.togetherPlayMusicIndex,
      musicSheet: useStore().togetherRoomInfo.togetherPlayMusicSheet
    }
    let message = {
      type: 1,
      data: data
    }
    sendWsRequest(websocket, message)

    // 播放状态同步
    if (useStore().togetherRoomInfo.togetherPlayStatus) {
      message = {
        type: 2,
        data: null
      }
      sendWsRequest(websocket, message)
    } else {
      message = {
        type: 3,
        data: null
      }
      sendWsRequest(websocket, message)
    }

    // 进度同步
    data = {
      content: position.value
    }
    message = {
      type: 4,
      data: data
    }

    sendWsRequest(websocket, message)
  }, 5000)


}

watch(() => props.song, (newValue, oldValue) => {
  loadAudio()
  // playAudio()
}, { deep: true })

watch(() => props.downPosition, (newValue, oldValue) => {
  // 当收到拉进度消息时，进行进度数据传递
  position.value = newValue
  audio.value.currentTime = position.value / 100 * audio.value.duration

})


</script>

<template>
    <div class="music-player">
      <!-- 播放控制 -->
      <div class="left-controls">
        <span @click="preSong">
          <i class="prePlay-icon"></i>
        </span>
        <span>
          <i class="play-icon" @click="playAudio()" v-if="!useStore().togetherRoomInfo.togetherPlayStatus"></i>
          <i class="pause-icon" @click="pauseAudio()" v-else></i>
        </span>
        <span @click="nextSong">
          <i class="nextPlay-icon"></i>
        </span>
      </div>

      <img class="cover" :src="song.cover">
      <div style="display: flex;flex-direction: column;margin-right: 150px;width: 100%">
        <p style="display: flex;justify-content: space-between;font-size: 15px;color: #e8e8e8;opacity: 0.8">
          <div>
            <span style="">{{ song.title }}</span> - <span>{{ song.musician }}</span>
          </div>
          <div>
            <span>{{ formatTime(audio.currentTime) }}</span> / <span>{{ formatTime(duration) }}</span>
          </div>
        </p>
        <el-slider step="0.1" class="song-slider" v-model="position" @change="updatePosition" @mousedown="isDragging = true"
                   @mouseup="isDragging = false" :show-tooltip="false" />
      </div>


      <div style="margin-left: auto" class="right-controls">
        <i class="download-icon"></i>
        <i class="volume-icon"></i>
        <el-slider style="width: 80px" v-model="volume" @input="updateVolume" />
      </div>
    </div>

</template>




<style scoped>
* {
  font-family: poppin,Tahoma,Arial,\5FAE\8F6F\96C5\9ED1,sans-serif;
}
.music-player {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, #4d4d4d, #313131);
  color: white;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 17% 15px;
}

i {
  display: inline-block;
  background: url("/src/assets/img/total4.png");
  opacity: 0.8;
  transform: scale(0.5);
  cursor: pointer;
}
i:hover {
  opacity: 1;
}
.play-icon {
  background-position: 0 0;
  width: 42px;
  height: 58px;
  margin: 0 10px;
}
.pause-icon {
  background-position: -60px 0;
  width: 42px;
  height: 58px;
  margin: 0 10px;
}
.prePlay-icon {
  width: 58px;
  height: 40px;
  background-position: 0 -60px;
}
.nextPlay-icon {
  width: 58px;
  height: 40px;
  background-position: 0 -104px;
}
.volume-icon {
  width: 52px;
  height: 42px;
  background-position: 0 -288px;
}
.download-icon {
  width: 44px;
  height: 42px;
  background-position: 0 -240px;
}
.cover {
  width: 50px;
  height: 50px;
  border-radius: 5px;
  margin-right: 20px;
  margin-left: 50px;
}

.left-controls, .right-controls {
  display: flex;
  align-items: center;
}
.song-slider {
  margin-left: 5px;
}

</style>


